Create and Query a Time Series Collection

您所在的位置:网站首页 mongodb datetime Create and Query a Time Series Collection

Create and Query a Time Series Collection

2023-11-12 01:26| 来源: 网络整理| 查看: 265

Docs Home → MongoDB Manual

Create and Query a Time Series Collection

On this page

Create a Time Series CollectionInsert Measurements into a Time Series CollectionQuery a Time Series CollectionRun Aggregations on a Time Series Collection

This page shows how to create and query a time series collection, with code examples.

ImportantFeature Compatibility Version Requirement

You can only create time series collections on a system with featureCompatibilityVersion set to 5.0 or greater.

Create a Time Series Collection1

Create the collection using either the db.createCollection() method or the create command. For example:

db.createCollection("weather",{ timeseries: { timeField: "timestamp", metaField: "metadata"}})2

Set the timeField to the field that contains time data, and the metaField to the field that contains metadata:

timeseries: { timeField: "timestamp", metaField: "metadata"}3

Define the time interval for each bucket of data using one of the two approaches below. For more detailed information, see Set Granularity for Time Series Data.

ImportantChanging Time Series Granularity

After creation, you can modify granularity or bucket definitions using the collMod method. However, you can only increase the timespan covered by each bucket. You cannot decrease it.

Define a granularity field:

timeseries: { timeField: "timestamp", metaField: "metadata", granularity: "seconds"}

OR

In MongoDB 6.3 and higher, you can define bucketMaxSpanSeconds and bucketRoundingSeconds fields. Both values must be the same:

timeseries: { timeField: "timestamp", metaField: "metadata", bucketMaxSpanSeconds: "300", bucketRoundingSeconds: "300"}4

Optionally, set expireAfterSeconds to expire documents when the value of the timeField is at least that old:

timeseries: { timeField: "timestamp", metaField: "metadata", granularity: "seconds", expireAfterSeconds: "86400"}Time Series Field Reference

A time series collection includes the following fields:

FieldTypeDescriptiontimeseries.timeFieldstring

Required. The name of the field which contains the date in each time series document. Documents in a time series collection must have a valid BSON date as the value for the timeField.

timeseries.metaFieldstring

Optional. The name of the field which contains metadata in each time series document. The metadata in the specified field should be data that is used to label a unique series of documents. The metadata should rarely, if ever, change.

The name of the specified field may not be _id or the same as the timeseries.timeField. The field can be of any type.

timeseries.granularityinteger

Optional. Do not use if setting bucketRoundingSeconds and bucketMaxSpanSeconds.

Possible values are seconds (default), minutes, and hours.

Set granularity to the value that most closely matches the time between consecutive incoming timestamps. This improves performance by optimizing how MongoDB stores data in the collection.

For more information on granularity and bucket intervals, see Set Granularity for Time Series Data.

timeseries.bucketMaxSpanSecondsinteger

Optional. Use with bucketRoundingSeconds as an alternative to granularity. Sets the maximum time between timestamps in the same bucket.

Possible values are 1-31536000.

New in version 6.3.

timeseries.bucketRoundingSecondsinteger

Optional. Use with bucketMaxSpanSeconds as an alternative to granularity. Must be equal to bucketMaxSpanSeconds.

When a document requires a new bucket, MongoDB rounds down the document's timestamp value by this interval to set the minimum time for the bucket.

New in version 6.3.

expireAfterSecondsintegerOptional. Enable the automatic deletion of documents in a time series collection by specifying the number of seconds after which documents expire. MongoDB deletes expired documents automatically. See Set up Automatic Removal for Time Series Collections (TTL) for more information.

Other allowed options that are not specific to time series collections are:

storageEngine

indexOptionDefaults

collation

writeConcern

comment

TipSee:

db.createCollection() and create.

Insert Measurements into a Time Series Collection

Each document you insert should contain a single measurement. To insert multiple documents at once, issue the following command:

db.weather.insertMany( [ { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-18T00:00:00.000Z"), "temp": 12 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-18T04:00:00.000Z"), "temp": 11 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-18T08:00:00.000Z"), "temp": 11 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-18T12:00:00.000Z"), "temp": 12 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-18T16:00:00.000Z"), "temp": 16 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-18T20:00:00.000Z"), "temp": 15 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-19T00:00:00.000Z"), "temp": 13 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-19T04:00:00.000Z"), "temp": 12 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-19T08:00:00.000Z"), "temp": 11 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-19T12:00:00.000Z"), "temp": 12 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-19T16:00:00.000Z"), "temp": 17 }, { "metadata": { "sensorId": 5578, "type": "temperature" }, "timestamp": ISODate("2021-05-19T20:00:00.000Z"), "temp": 12 }] )

To insert a single document, use the db.collection.insertOne() method.

TipOptimize Insert Performance

To learn how to optimize inserts for large operations, see Optimize Inserts.

Query a Time Series Collection

You query a time series collection the same way you query a standard MongoDB collection.

To return one document from a time series collection, run:

db.weather.findOne({ "timestamp": ISODate("2021-05-18T00:00:00.000Z")})

Example output:

{ timestamp: ISODate("2021-05-18T00:00:00.000Z"), metadata: { sensorId: 5578, type: 'temperature' }, temp: 12, _id: ObjectId("62f11bbf1e52f124b84479ad")}Run Aggregations on a Time Series Collection

For additional query functionality, use an aggregation pipeline such as:

db.weather.aggregate( [ { $project: { date: { $dateToParts: { date: "$timestamp" } }, temp: 1 } }, { $group: { _id: { date: { year: "$date.year", month: "$date.month", day: "$date.day" } }, avgTmp: { $avg: "$temp" } } }] )

The example aggregation pipeline groups all documents by the date of the measurement and then returns the average of all temperature measurements that day:

{ "_id" : { "date" : { "year" : 2021, "month" : 5, "day" : 18 } }, "avgTmp" : 12.714285714285714}{ "_id" : { "date" : { "year" : 2021, "month" : 5, "day" : 19 } }, "avgTmp" : 13}←  Time SeriesList Time Series Collections in a Database →


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3